package com.star.mianshidog.blackfilter;

import com.star.mianshidog.utils.NetUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * packageName com.star.mianshidog.blackfilter
 *
 * @author zerostart
 * @className BlackIpFilter
 * @date 2024/10/9
 * @description
 * 全局IP黑名单过滤器
 * 1.WebFilter的优先级高于@Aspect切面
 * - wenFilter： 首先，WebFilter拦截Http请求，并可以根据逻辑决定是否继续执行
 * - SpringAoP切面： 如果请求经过过滤器并进入Spring管理的bean，此时切面生效，对匹配的bean方法进行拦截
 * - controller层：如果@Aspect没有阻止执行，最终请求到达controller或@RestController层
 *
 */

@WebFilter(urlPatterns = "/*", filterName = "blackIpFilter")
public class BlackIpFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        String ipAddress = NetUtils.getIpAddress((HttpServletRequest) servletRequest);
        if (BlackIpUtils.isBlackIp(ipAddress)) {
            servletResponse.setContentType("text/json;charset=utf-8");
            servletResponse.getWriter().write("{\"errorCode\":\"-1\",\"errorMsg\":\"黑名单IP，禁止访问\"}");
            return;
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
